package com.example.demo.config;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class JdkProxyHandler implements InvocationHandler {

  /**
   * target
   */
  private Object object;

  public Object createProxy(Object o){
    this.object = o;
    return Proxy.newProxyInstance(object.getClass().getClassLoader(),object.getClass().getInterfaces(),this);
  }

  public void before(Object target, Method method, Object[] args) {
    log.info(">>>>>>> {} before", method.getName());
  }

  public boolean condition(Object target, Method method, Object[] args){
    return true;
  }

  public void after(Object result, Method method){
    log.info(">>>>>>> {} after", method.getName());
  }

  @Override
  public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    //调用被代理者的方法
    if(condition(proxy, method, args)){
      before(proxy, method, args);
    }
    Object result = method.invoke(object,args);
    if(condition(proxy, method, args)){
      after(result, method);
    }
    return result;
  }
    
}